package com.lyl.xxx.modules.web.account.service.impl;

import cn.hutool.core.date.DateUtil;
import com.lyl.common.exception.BizException;
import com.lyl.common.util.ContextHolderUtil;
import com.lyl.xxx.common.constants.RedisConstant;
import com.lyl.xxx.common.utils.AddressUtils;
import com.lyl.xxx.common.utils.IpUtils;
import com.lyl.xxx.common.utils.RedisUtil;
import com.lyl.xxx.modules.framework.security.model.details.LoginDetails;
import com.lyl.xxx.modules.framework.security.service.TokenService;
import com.lyl.xxx.modules.system.account.entity.SysUser;
import com.lyl.xxx.modules.system.account.service.SysUserService;
import com.lyl.xxx.modules.web.account.model.dto.LoginDTO;
import com.lyl.xxx.modules.web.account.service.LoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Mr.Luo
 * @date 2022-09-19 11:42
 * @desc
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;
    private final TokenService tokenService;
    private final SysUserService sysUserService;

    @Override
    public String login(LoginDTO dto) {
        Authentication authenticate;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword());
            authenticate = authenticationManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } catch (BadCredentialsException e) {
            throw new BizException("用户名密码错误");
        } catch (AuthenticationException e) {
            throw new BizException(e.getMessage());
        }
        LoginDetails loginDetails = (LoginDetails) authenticate.getPrincipal();
        //记录登录信息
        recordLoginInfo(loginDetails);
        return tokenService.refreshToken(loginDetails);
    }

    private void recordLoginInfo(LoginDetails loginDetails) {
        SysUser sysUser = loginDetails.getSysUser();
        HttpServletRequest request = ContextHolderUtil.getRequest();
        sysUser.setLoginIp(IpUtils.getIpAddr(request))
                .setLoginDate(DateUtil.now())
                .setUpdateBy(sysUser.getUserName());
        sysUserService.updateById(sysUser);

        //设置浏览器相关信息
        assert request != null;
        loginDetails.setLoginAddress(AddressUtils.getRealAddressByIP(sysUser.getLoginIp()))
                .setOs(AddressUtils.getOsName(request))
                .setBrowser(AddressUtils.getBrowserName(request));
    }

    @Override
    public boolean logout(Long userId, String token) {
        log.info("方法名: logout,  请求参数: userId = [" + userId + "], token = [" + token + "]");
        //1. 移除redis中token
        RedisUtil.del(RedisConstant.LOGIN_TOKEN + token);
        //2. 保存日志

        //3.
        return true;
    }
}
